# coding:utf8
"""mail 互交小程序的指令操作
    包含：
        1. send ip
        2. send data usage
        3. get command: shutdown power
        4. 文件共享. -- WsgiDAV
    全部用 类 写。
"""
import sys
sys.path.extend(['C:\\Py',
                 'C:\\Py\\WiFi',
                 'C:\\Py\\Python',
                 'C:\\Py\\study',
                 'C:\\Py\\e_mail',
                 'C:\\Py\\IO_file',
                 ])

import time
import socket
import os
from e_mail.send.cl_send_mail import SendMail
from psutil import net_io_counters

__all__ = ['dic_sender', 'SendIP', 'SendDataUsage']
# -------- 常量 ------
dic_sender = {'pop_host': 'pop.qq.com',
              'smtp_host': 'smtp.qq.com',
              'user': '1491311784@qq.com',
              'passwd': 'fxvvlznnwkclheic',
              'receiver': 'lee_cq@icloud.com'
              }
# --------  ---------


class SendIP(SendMail):
    """发送IP地址到邮箱"""

    def __init__(self, smtp_host, user, passwd, **kwargs):
        super().__init__(smtp_host, user, passwd, **kwargs)
        self.ipv4 = socket.gethostbyname(socket.gethostname())
        self.subject = f'Now {time.strftime("%H:%M", time.localtime())} IPv4 Address'
        self.msg = self.ipv4
        self.send_mail()


class SendDataUsage(SendMail):
    """发送 数据使用情况到 邮箱"""
    f_EVERY_10MIN = './_sup/every_10minData.ini'
    f_SEND_LOG = './_sup/sendLog.log'

    def __init__(self, smtp_host, user, passwd, *args, **kwargs):
        super().__init__(smtp_host, user, passwd, *args, **kwargs)
        self.init_data = self.get_now_net()
        self.init_time = self.now_second()
        self.now_data = self.get_now_net()

        self.write_file(self.f_EVERY_10MIN, 'w', self.init_data)

    #

    def send_all_data_usage(self):
        _amount = self.calculate_amount(self.init_data, self.get_now_net())
        _rate = self.calculate_rate(_amount, self.now_second()-self.init_time)
        _amount_b = [self.calculate_unit_b(_amount[0]), self.calculate_unit_b(_amount[1])]
        _rate_b = [self.calculate_unit_b(_rate[0]), self.calculate_unit_b(_rate[1])]
        _amount_p = [self.calculate_unit_p(_amount[2]), self.calculate_unit_p(_amount[3])]
        _rate_p = [self.calculate_unit_p(_rate[2]), self.calculate_unit_p(_rate[3])]

    @staticmethod
    def calculate_rate(_amount, _delta_t):
        """:return 4个值 发送比特，接受比特，发送包，接受包 - 平均速率"""
        # if not isinstance(_amount, list) or not isinstance(_amount, tuple): _amount = [_amount]
        _r = []
        for rate in _amount:
            _r.append(rate / _delta_t)
        return _r

    @staticmethod
    def calculate_amount(_start, _end):
        """
        :param _start: 包含4个值的元组，一般是 self.get_net_str()的返回值。
        :param _end: 同上。
        :return 4个值 发送比特，接受比特，发送包，接受包 - 起止 差值。
        """
        _r = []
        if len(_start) == len(_end):
            for x in range(len(_start)):
                _r.append(_end[x] - _start[x])
        return _r

    @staticmethod
    def calculate_unit_p(_data):
        """:return int(结果), str(单位)"""
        if _data < 1000 ** 1:
            return _data / 1000 ** 0, 'b'
        elif _data < 1000 ** 2:
            return _data / 1000 ** 1, 'Kb'
        elif _data < 1000 ** 3:
            return _data / 1000 ** 2, 'Mb'
        elif _data < 1000 ** 4:
            return _data / 1000 ** 3, 'Gb'
        elif _data < 1000 ** 5:
            return _data / 1000 ** 4, 'Tb'
        else:
            return ValueError

    @staticmethod
    def calculate_unit_b(_data):
        """:return int(结果), str(单位)"""
        if _data < 1000 ** 1:
            return _data / 1024 ** 0, 'b'
        elif _data < 1000 ** 2:
            return _data / 1024 ** 1, 'Kb'
        elif _data < 1000 ** 3:
            return _data / 1024 ** 2, 'Mb'
        elif _data < 1000 ** 4:
            return _data / 1024 ** 3, 'Gb'
        elif _data < 1000 ** 5:
            return _data / 1024 ** 4, 'Tb'
        else:
            return ValueError

    @staticmethod
    def get_now_net():
        """:return 4个值 发送比特，接受比特，发送包，接受包 - 实时量"""
        _net_io = net_io_counters()
        return _net_io.bytes_sent, _net_io.bytes_recv, _net_io.packets_sent, _net_io.packets_recv

    @staticmethod
    def write_file(file_name, _mode, content):
        with open(file_name, _mode, encoding='utf8') as _f:
            _f.write(str(content))

    @staticmethod
    def read_file(file_name):
        with open(file_name, 'a') as _f:
            return _f.read()

    @staticmethod
    def now_second():
        return int(time.time())


class Shutdown:
    """关机命令"""
    @staticmethod
    def at_now():
        os.system('shutdown /sg /t 60')
        
    @staticmethod
    def cancel_shutdown():
        os.system('shutdown /a')
        
    @staticmethod
    def at_time(_time):
        pass
        
    @staticmethod  
    def at_litter(_time):
        pass


if __name__ == '__main__':
    # SendIP(**dic_sender)
    Shutdown.at_now()
